package com.venue.hjt.venueclass.utlis;


import android.os.AsyncTask;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.util.Map;
import java.util.Set;

/**
 * Created by aoc on 2016/8/31.
 */

public class AsyncTaskSoapUtil extends AsyncTask<Void, Void, String> {

    private String name;
    private String url;
    private String action;
    private Map<String, String> param;
    private Callback callback;

    public AsyncTaskSoapUtil(String name, String url, String action, Map<String, String> param) {
        this.name = name;
        this.url = url;
        this.action = action;
        this.param = param;
    }

    public void setCallback(Callback callback) {
        this.callback = callback;
    }

    @Override
    protected void onPreExecute() {

    }

    @Override
    protected String doInBackground(Void... voids) {
        String xml = "";
        SoapObject request = new SoapObject(name, action);

        Set<Map.Entry<String, String>> set = param.entrySet();
        for (Map.Entry<String, String> entry : set) {
            request.addProperty(entry.getKey(), entry.getValue());
        }
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.dotNet = true;
        envelope.bodyOut = request;
        HttpTransportSE transportSE = new HttpTransportSE(url);
        try {
            transportSE.call(getSoapAction(name, action), envelope);
            // 获取返回的数据
            SoapObject object = (SoapObject) envelope.bodyIn;
            String result = object.getProperty(0).toString();
            //Object bodyIn =  envelope
            xml = result;
        }
        catch (SoapFault soapFault) {
            soapFault.printStackTrace();
        }
        catch (XmlPullParserException e) {
            e.printStackTrace();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return xml;
    }

    @Override
    protected void onPostExecute(String data) {
        callback.onPost(data);
    }

    public interface Callback {

        void onPost(String data);
    }

    private String getSoapAction(String name, String action) {
        StringBuilder builder = new StringBuilder();
        builder.append(name);
        builder.append(action);
        return builder.toString();
    }
}
